package com.wolfking.jeesite.aspect;

import com.wolfking.jeesite.config.SsoConfig;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class RootUrlAspect {

    @Autowired
    private SsoConfig ssoConfig;

    @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.GetMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PutMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
    public Object modelAddRootUrl(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        try {
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            Class<?>[] parameterTypes = method.getParameterTypes();
            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];
                if (Model.class.isAssignableFrom(parameterType)) {
                    Model model = (Model) args[i];
                    model.addAttribute("rootUrl", ssoConfig.getSelfRootUrlByRequest());
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return proceed;
    }
}
